from event import Event
import datetime

try: #this code block from pyXSD (http://pyxsd.org)
    import lxml.etree as ET #lxml uses libxml2, which is extra quick
except:
    try:    # Thanks to the ElementTree library (http://www.effbot.org/zone/element-index.htm)
        import cElementTree as ET
    except:
        try:
            from xml.etree import cElementTree as ET
        except:
            try:
                from xml.etree import ElementTree as ET
            except:
                try:
                    import elementtree.ElementTree as ET
                except:
                    raise ImportError, "Your system needs the ElementTree or cElementTree library in order to run this package"


class Schedule(object):
    def __init__(self, name):
        self.name   = name
        self.events = []

    def generateXML(self, filename):
        root       = ET.Element("schedule")
        root.set("name", name)
        eventsElem = ET.SubElement(root, "events")
        for event in self.events: event.buildXML(eventsElem)
        tree = ET.ElementTree(root)
        tree.write(filename)

    def addEventToSchedule(self,  name, startDatetime, endDatetime, description, location, allDay, repeatMethod=None, repeatDays=None):
        """
        Wrapper for the Event class. Adds the event to the schedules 'events' list.
        """
        self.evemts.append(Event(name, startDatetime, endDatetime, description, location, allDay, repeatMethod=None, repeatDays=None))

    def deleteEventFromScheduleByName(self, eventName):
        for i, event in enumerate(self.events):
            if event.name is eventName:
                del self.events[i]

    def deleteEventFromScheduleByDatetime(self, startDatetime, endDatetime=None):
        if endDatetime:
            for i, event in enumerate(self.events):
                if startDatetime is event.startDatetime and endDatetime is event.endDatetime:
                    del self.events[i]
        else:
            for i, event in enumerate(self.events):
                if startDatetime is event.startDatetime:
                    del self.events[i]

    def getEventNames(self):
        return [event.name for event in self.events]

    
    def makeScheduleFromXML(cls, filename):
        tree               = ET.parse(filename)
        root               = tree.getroot()
        scheduleObj        = cls(root.get("name"))
        eventsTag          = root.find("events")
        eventTags          = eventsTag.getchildren()
        scheduleObj.events = [ Event.makeEventFromXML(eventTag) for eventTag in eventTags ]
        return scheduleObj
     makeScheduleFromXML = classmethod( makeScheduleFromXML)
    
